package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.adpter.FinishSheetAdapter;
import com.xn.app.muying.adpter.UnfinishSheetAdapter;
import com.xn.app.muying.bean.FinishSheetBean;
import com.xn.app.muying.bean.UnfinishSheetBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Request;

/**
 * 解读历史
 * Created by Administrator on 2016/12/28.
 */
public class ReadHistoryActivity extends BaseActivity implements View.OnClickListener, MyListView.IXListViewListener {
    //未完成的化验单列表
    private MyListView lv;
    //数据库
    private DBManager db = null;
    //未完成的化验单列表的适配器
    private UnfinishSheetAdapter adapter;
    //已完成的化验单分类
    private GridView gridView;
    //未完成的化验单分类的适配器
    private FinishSheetAdapter finishSheetAdapter;
    private TextView unfinish, finish;
    //加载框
    AlertDialog dialog;
    //已完成化验单数据集合
    ArrayList<FinishSheetBean> list = null;
    //未完成化验单数据集合
    private ArrayList<UnfinishSheetBean> unlist = new ArrayList<>();
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    private Handler handler3 = new Handler();
    LinearLayout linearlayout;
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 10;
    //数据显示页面
    private LinearLayout data_linearlayout=null;
    //记录数据是否下载完成
    private int isTrue=0;
    //无数据显示页面
    private LinearLayout no_linearlayout1=null;
    private LinearLayout no_linearlayout2=null;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_readhistory);
        db = new DBManager(this);
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        initView();
    }

    private void initView() {
        TextView title_name = (TextView) findViewById(R.id.title_name);
        ImageView img_back = (ImageView) findViewById(R.id.img_back);
        lv = (MyListView) findViewById(R.id.activity_readhistory_lv);
        gridView = (GridView) findViewById(R.id.activity_readhistory_gridview);
        unfinish = (TextView) findViewById(R.id.activity_readhistory_unfinish);
        finish = (TextView) findViewById(R.id.activity_readhistory_finish);
        linearlayout = (LinearLayout) findViewById(R.id.linearlayout);
        data_linearlayout = (LinearLayout) findViewById(R.id.data_linearlayout);
        no_linearlayout1 = (LinearLayout) findViewById(R.id.no_linearlayout1);
        no_linearlayout2 = (LinearLayout) findViewById(R.id.no_linearlayout2);
        adapter = new UnfinishSheetAdapter(ReadHistoryActivity.this);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (unlist != null) {
                    Intent intent = new Intent();
                    intent.putExtra("id", unlist.get(i).getId());
                    intent.putExtra("ProcessStatus", unlist.get(i).getProcessStatus());
                    intent.setClass(ReadHistoryActivity.this, UnfinishInfoActivity.class);
                    startActivity(intent);
                }
            }
        });
        finishSheetAdapter = new FinishSheetAdapter(ReadHistoryActivity.this, handler3, imageLoader, options);
        gridView.setAdapter(finishSheetAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (list != null) {
                    Intent intent = new Intent();
                    intent.putExtra("id", list.get(i).getId());
                    intent.putExtra("DisplayName", list.get(i).getDisplayName());
                    intent.setClass(ReadHistoryActivity.this, FinishListActivity.class);
                    startActivity(intent);
                }
            }
        });
        if (NetworkUtil.isNetworkAvailable(ReadHistoryActivity.this)) {
            unfinish.setVisibility(View.GONE);
            finish.setVisibility(View.GONE);
            dialog = new MyAlertDialog().ShowDialog(ReadHistoryActivity.this, R.layout.dialog_loading);
            getUnfinishSheet();//未完成单验单数据下载
            getFinishSheet();//已完成化验单数据下载
        } else {
            ToastUtil.showToast(ReadHistoryActivity.this, R.string.no_network_hint);
        }

        title_name.setText("解读历史");
        img_back.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
        }
    }

    private void getFinishSheet() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.FinishSheet).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler2.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler2.sendMessage(msg1);
                    }
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }).start();
    }

    Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            isTrue=isTrue+1;
            switch (msg.what) {
                case 0:
                    onJsonFinishData(msg.obj.toString());
                    break;
                case 1:
                    ToastUtil.showToast(ReadHistoryActivity.this, "获取数据失败");
                    break;
            }
        }
    };

    private void onJsonFinishData(String bodys) {
        try {
            JSONArray jsonArray = new JSONArray(bodys);
            list = new ArrayList<>();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String pictureUrl = jsonObject.optString("pictureUrl");
                String displayName = jsonObject.optString("displayName");
                String reportCount = jsonObject.optString("reportCount");
                String id = jsonObject.optString("id");
                FinishSheetBean finishSheetBean = new FinishSheetBean();
                finishSheetBean.setPictureUrl(pictureUrl);
                finishSheetBean.setDisplayName(displayName);
                finishSheetBean.setReportCount(reportCount);
                finishSheetBean.setId(id);
                list.add(finishSheetBean);
            }
            finishSheetAdapter.getData(list);
            if(list.size()>0){
                if(gridView.getVisibility()==View.GONE){
                    gridView.setVisibility(GridView.VISIBLE);
                }
                if(no_linearlayout2.getVisibility()==View.VISIBLE){
                    no_linearlayout2.setVisibility(LinearLayout.GONE);
                }
            }else{
                if(gridView.getVisibility()==View.VISIBLE){
                    gridView.setVisibility(GridView.GONE);
                }
                if(no_linearlayout2.getVisibility()==View.GONE){
                    no_linearlayout2.setVisibility(LinearLayout.VISIBLE);
                }
            }
          if(isTrue==2){
              data_linearlayout.setVisibility(View.VISIBLE);
          }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void getUnfinishSheet() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.UnfinishSheet(currentPage, number)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (dialog != null) {
                unfinish.setVisibility(View.VISIBLE);
                finish.setVisibility(View.VISIBLE);
                dialog.dismiss();
            }
            isTrue=isTrue+1;
            switch (msg.what) {
                case 0:
                    onJsonData(msg.obj.toString());
                    break;
                case 1:
                    ToastUtil.showToast(ReadHistoryActivity.this, "获取数据失败");
                    break;
            }
        }
    };

    private void onJsonData(String bodys) {
        try {
            String type = getIntent().getStringExtra("data");
            JSONObject jsonObject = new JSONObject(bodys);
            totalCount = jsonObject.getInt("totalCount");
            JSONArray items = jsonObject.getJSONArray("items");
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String processStatus = object.optString("processStatus");
                String reporterDate = object.optString("reporterDate");
                String id = object.optString("id");
                UnfinishSheetBean unfinishSheetBean = new UnfinishSheetBean();
                unfinishSheetBean.setProcessStatus(processStatus);
                unfinishSheetBean.setReporterDate(reporterDate);
                unfinishSheetBean.setId(id);
                unlist.add(unfinishSheetBean);
            }
            onLoad();
            lv.setPullLoadEnable(true);
            lv.setXListViewListener(ReadHistoryActivity.this, totalCount, currentPage, number);
            adapter.getData(unlist);
            if(unlist.size()>0){
                if(lv.getVisibility()==View.GONE){
                    lv.setVisibility(ListView.VISIBLE);
                }
                if(no_linearlayout1.getVisibility()==View.VISIBLE){
                    no_linearlayout1.setVisibility(ListView.GONE);
                }
            }else{
                if(lv.getVisibility()==View.VISIBLE){
                    lv.setVisibility(ListView.GONE);
                }
                if(no_linearlayout1.getVisibility()==View.GONE){
                    no_linearlayout1.setVisibility(ListView.VISIBLE);
                }
            }
            if(isTrue==2){
                data_linearlayout.setVisibility(View.VISIBLE);
            }
            if (type.equals("1")&&linearlayout.getVisibility()==0) {
                linearlayout.setVisibility(LinearLayout.GONE);
            }
            if (getIntent().getStringExtra("data") != null && !getIntent().getStringExtra("data").equals("") && !getIntent().getStringExtra("data").equals("null")&& !getIntent().getStringExtra("data").equals("1")) {
                TextView time = (TextView) findViewById(R.id.time);
                time.setText(getIntent().getStringExtra("data"));
                linearlayout.setVisibility(LinearLayout.VISIBLE);
                no_linearlayout1.setVisibility(LinearLayout.GONE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (NetworkUtil.isNetworkAvailable(ReadHistoryActivity.this)) {
            if(unlist!=null&&unlist.size()>0){
                lv.setSelection(0);
            }
            unlist = new ArrayList<>();
            getUnfinishSheet();//未完成单验单数据下载
            getFinishSheet();//已完成化验单数据下载
        } else {
            ToastUtil.showToast(ReadHistoryActivity.this, R.string.no_network_hint);
        }

    }


    //上拉加载
    public void onLoadMore() {
        if (NetworkUtil.isNetworkAvailable(ReadHistoryActivity.this)) {
            if (totalCount > currentPage * number) {
                currentPage = currentPage + 1;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(AppConstant.THREAD_SLEEP);
                            getUnfinishSheet();//未完成单验单数据下载
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            } else {
                onLoad();
            }
        } else {
            onLoad();
            ToastUtil.showToast(ReadHistoryActivity.this, R.string.no_network_hint);
        }
    }

    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        lv.stopLoadMore();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
